package com.bdqn.t350.ch11.service.imp;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bdqn.t350.ch11.bean.Role;
import com.bdqn.t350.ch11.bean.User;
import com.bdqn.t350.ch11.exception.CustomException;
import com.bdqn.t350.ch11.mapper.RoleMapper;
import com.bdqn.t350.ch11.mapper.UserMapper;
import com.bdqn.t350.ch11.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImp implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public List<Role> selectList(IPage<Role> page, Role role) {
        return roleMapper.selectList(page, role);
    }

    @Override
    public List<Role> selectByRoleId(Role role) {
        return roleMapper.selectByRoleId(role);
    }

    @Transactional
    public boolean insert(Role role) {
        boolean bool = true;
        try {
            int count = roleMapper.insert(role);
            if (count > 0) {
                for (User user : role.getUsers()) {
                    if (user.getUsrName() != null && !user.getUsrName().equals("")) {
                        user.setUsrRoleId(role.getRoleId());
                        userMapper.insert(user);
                    }
                    System.out.println(1 / 0);
                }
            } else {
                bool = false;
            }
            return bool;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("自定义异常....添加角色失败");
            //return bool;
        }
    }

    @Override
    public List<String> getRightByRoleId(Integer roleId) {
        return roleMapper.getRightByRoleId(roleId);
    }
}
